from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
import json

class ConfigWindow(Popup):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.title = '配置 OpenAI API'
        self.size_hint = (0.8, 0.8)
        
        self.layout = BoxLayout(orientation='vertical')
        
        # TextInput for Safety Key
        self.safety_key_input = TextInput(hint_text='输入 Safety Key', multiline=False)
        self.layout.add_widget(self.safety_key_input)
        
        # TextInput for Base Address
        self.base_address_input = TextInput(hint_text='输入 Base Address', multiline=False)
        self.layout.add_widget(self.base_address_input)
        
        # TextInput for Model Name
        self.model_name_input = TextInput(hint_text='输入 Model Name', multiline=False)
        self.layout.add_widget(self.model_name_input)
        
        # Save Button
        self.save_button = Button(text='保存')
        self.save_button.bind(on_press=self.save_config)
        self.layout.add_widget(self.save_button)
        
        self.content = self.layout
    
    def save_config(self, instance):
        safety_key = self.safety_key_input.text
        base_address = self.base_address_input.text
        model_name = self.model_name_input.text
        
        config = {
            "safety_key": safety_key,
            "base_address": base_address,
            "model_name": model_name
        }
        
        with open('config.json', 'w') as f:
            json.dump(config, f)
        
        print(f'保存配置: Safety Key={safety_key}, Base Address={base_address}, Model Name={model_name}')
        self.dismiss()

def show_config_window():
    config_window = ConfigWindow()
    config_window.open()